import axios from "axios";
import { getToken, setToken, removeToken } from "@/utils/storage/token";
import { ElMessage } from "element-plus";
import { encryptData, decryptData } from "./sm4Util";
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL, // 基础url
  withCredentials: false, // 发送cookie
  timeout: 500000, // 请求超时时长
});
// request请求
service.interceptors.request.use(
  (config: any) => {
    config.headers["jsonType"] = "jsonType";
    if (getToken()) {
      config.headers[import.meta.env.VITE_AUTHOR_KEY] = getToken();
    }
    if (
      import.meta.env.VITE_PROJECT_TYPE === "PRO" &&
      config.method === "post" &&
      config.data
    ) {
      config.data = { encryptData: encryptData(config.data) };
    }
    return config;
  },
  (error) => {
    // 请求错误
    return Promise.reject(error);
  }
);
// response返回
service.interceptors.response.use(
  (response) => {
    if (typeof response.data.size === "undefined") {
      const res = response.data;
      if (import.meta.env.VITE_PROJECT_TYPE === "PRO") {
        res.data = decryptData(res.data);
      }
      if (res.errorCode === 33061) {
        // 用户未登录
        removeToken();
        location.reload();
        return;
      }
      if (res.errorCode === 30250 || res.errorCode === 30256) {
        // 报价超过权限
        return res;
      }
      if (res.errorCode !== 0) {
        // 数据异常抱错
        ElMessage.error(res.message);
        return Promise.reject(new Error(res.message || "Error"));
      }
      const _token = response.headers[import.meta.env.VITE_AUTHOR_KEY];
      if (
        _token &&
        typeof _token !== undefined &&
        typeof _token !== "undefined"
      ) {
        setToken(_token);
      }
      return res;
    } else {
      return response;
    }
  },
  (error) => {
    // removeToken();
    // location.reload();
    // ElMessage.error(error.message);
    // return Promise.reject(error);
  }
);

export default service;
